package com.sudo.sso.server.api.wx;

import cn.dev33.satoken.dao.SaTokenDao;
import com.boot.starter.redis.component.RedisKeys;
import com.sudo.boot.base.constant.enums.EnumScanLogin;
import com.sudo.boot.base.pojo.JsonRes;
import com.sudo.boot.base.util.BootEnumUtil;
import com.sudo.boot.weixin.serivce.Oauth2Service;
import com.sudo.boot.weixin.util.WxUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/ss/wx-login")
@RequiredArgsConstructor
public class WxUserController {
    private final Oauth2Service oauth2Service;
    private final SaTokenDao saTokenDao;

    @GetMapping("/qrcode")
    public JsonRes<String> qrCode(@RequestParam String loginCode) {
        String state = WxUtil.LOGIN + loginCode;
        // 设置二维码的过期时间为5分钟
        String qrCodeBind = RedisKeys.qrCodeOverdue(state);
        saTokenDao.set(qrCodeBind, "1", 300);
        String qrCodeUrl = oauth2Service.createQrCodeUrl(state);
        log.info("生成微信登录授权二维码：{}", qrCodeUrl);
        return JsonRes.ok(qrCodeUrl);
    }

    @GetMapping("/loginStatus")
    public JsonRes<Object> loginStatus(@RequestParam String loginCode) {
        // 设置本次扫码登录会话状态
        String scanLoginStatus = RedisKeys.scanLoginStatus(loginCode);
        Object object = saTokenDao.get(scanLoginStatus);
        if (Objects.isNull(object)) {
            return JsonRes.ok();
        }
        if (!EnumScanLogin.LOGIN_SUCCESS.getCode().equals(object)) {
            saTokenDao.delete(scanLoginStatus);
        }
        String desc = BootEnumUtil.getDescByCode(EnumScanLogin.class, object);
        return JsonRes.ok(object,desc);
    }
}
